<template>
  <div style="border: 1px solid #ddd;padding: 15px 0;">
    <template v-for="(item, index) in param.contactList" :key="index">
        <el-form :model="param.contactList[index]" :inline="true" :ref="(el: any) => { ruleFormRef[index] = el }" label-width="auto" :rules="rules">
          <el-row :justify="'start'" style="padding: 10px 0;">
            <el-col :span="6">
              <el-form-item label="联系人" prop="contacts" style="margin: 0 20px 0 0">
                  <el-input v-model="item.contacts"  clearable class="div-diy" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="联系方式" prop="areaCode" style="margin: 0;">
                <areaTel ref="areaTelRef" v-model:firstValue="item.tel" v-model:secondValue="item.areaCode" @inputValTel="inputValTel" @changeTag="changeTag" style="width:100%"></areaTel>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="邮箱" prop="email" style="margin: 0;">
                <el-input v-model.trim="item.email" clearable class="div-diy" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="2">
              <el-row justify="start" style="margin-top: 5px;">
                <el-col :span="10" v-if="param.contactList.length - 1 > 0" @click="handleDelete(index)" align="middle">
                  <el-button  size="small" icon="Delete" type="danger" circle plain> </el-button>
                </el-col>
                <el-col :span="10" v-if="param.contactList.length - 1 == index && param.contactList.length < 3" align="middle">
                  <el-button @click="handleAdd" icon="Plus" type="primary" size="small" circle plain></el-button>  
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
    </template>
  </div>
</template>

<script setup lang="ts">
import areaTel from '@/views/components/areaTel'
import { FormInstance } from 'element-plus';
import { ref, reactive, onMounted, watch, onActivated, onDeactivated } from 'vue'

const ruleFormRef = ref([])

const props = defineProps({
  rowData: { // 未用
    type: Object,
    default: () => { }
  },
  disabled: {
    type: Boolean,
    default: false
  },
  yardContacts: {
    type: String,
    default: ''
  }
})
const param = ref({
  contactList: [{ "tel": "", "email": "", "areaCode": "86", "contacts": "" }]
})

onMounted(() => {
  getSetContactList(props.yardContacts)
})
watch(() => props.yardContacts, (newVal, oldVal) => {
  getSetContactList(props.yardContacts)
})

//初始化
const getSetContactList = (val) => {
  if (val) {
    param.value.contactList = JSON.parse(val)
  } else {
    param.value.contactList = [{ "tel": "", "email": "", "areaCode": "86", "contacts": "" }]
  }
}

onDeactivated(() => {
  ruleFormRef.value.forEach((item) => {
    resetForm(item)
  })
})



const inputTel = ref('');
const inputValTel = (val)=>{ 
  inputTel.value = val;
}
const areaTelRef = ref()
const changeTags = ref(false)
const changeTag = (val) =>{
  changeTags.value = true
}

//校验 
const rules = reactive({
  contacts: [ //10个字
    { required: true, message: '必填项', trigger: 'blur' },
    { max: 200, trigger: "blur", message: "不能超过200个字符" },
    {
      validator:(rule: any, value: any, callback: any) => {
        if (!value) {
          callback(new Error('必填项'));
        }
        // 判断是否为纯汉字
        if(/^[\w\u4e00-\u9fa5\p{P}\s]+$/u.test(value)){
          callback(); // 校验通过
        }else{
          callback(new Error('只能输入文字/数字/符号'));
        }
      }
    }
  ],
  areaCode: [
    { required: true, message: '必填项', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if(changeTags.value){
          switch (value) {
            case '86': // 中国大陆
              const regex = /^(?:(?:\+|00)86)?1\d{10}$/
              if(inputTel.value.length != 11 && !regex.test(inputTel.value)){ 
                callback(new Error('中国手机号长度为11位数字,且为1开头'));
              }else{
                callback(); // 校验通过
              }
              break;
            case '7': // 哈萨克斯坦 俄罗斯
              if(inputTel.value.length != 10){
                callback(new Error('该国手机号长度为10位数字'));
              }else{
                callback(); // 校验通过
              }
              break;
            case '49': // 德国
              if(inputTel.value.length != 10){
                callback(new Error('该国手机号长度为10位数字'));
              }else{
                callback(); // 校验通过
              }
              break;
            case '998': // 乌兹别克斯坦
              if(inputTel.value.length != 9){
                callback(new Error('该国手机号长度为9位数字'));
              }else{
                callback(); // 校验通过
              }
              break;
            // case '7': // 俄罗斯
            //   if(inputTel.value.length != 10){
            //     callback(new Error('该国手机号长度为10位数字'));
            //   }else{
            //     callback(); // 校验通过
            //   }
            //   break;
            case '8': // 俄罗斯
              if(inputTel.value.length != 10){
                callback(new Error('该国手机号长度为10位数字'));
              }else{
                callback(); // 校验通过
              }
              break;
            case '375': // 白俄罗斯
              if(inputTel.value.length != 9){
                callback(new Error('该国手机号长度为9位数字'));
              }else{
                callback(); // 校验通过
              }
              break;
            default:
              callback(); // 校验通过
          }
        }else{
          callback();
        }
      }
    }

  ],
  email: [
    { required: true, message: '必填项', trigger: 'change' },
    { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
  ],
 
})


//
const handleAdd = () => {
  param.value.contactList.push({ "tel": "", "email": "", "areaCode": "86", "contacts": "" })
}
const handleDelete = (subscript: any) => {
  // param.value.contactList.splice(index, 1)
  param.value.contactList = param.value.contactList.filter((_, index) => index !== subscript)
 
}

//validate
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  let resut = false
  await formEl.validate((valid, fields) => {
    if (valid) {
      resut = true
    } else {
      resut = false
    }
  })
  return resut
}
const validResult = async () => {
  let resut = true
  for (let i = 0; i < ruleFormRef.value.length; i++) {
    if(ruleFormRef.value[i] != null){
      let item = ruleFormRef.value[i]
      let res = await submitForm(item)
      if (!res) {
        resut = false
      }
    }
    
  }
  return resut
}

//重置validate
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 重置 所有联系人信息
const resetAll = () => {
  param.value.contactList = [{ "tel": "", "email": "", "areaCode": "86", "contacts": "" }]
}
const getContactList = () => {
  let list: any = []
  const contactList = param.value.contactList
  if (contactList.length > 0 && contactList[0].contacts) {
    list = contactList
  }
  return list
}


defineExpose({
  getContactList,
  validResult: validResult,
  resetAll
})

</script>
<style scoped></style>

